package com.pango.core.report;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.support.WebApplicationContextUtils;

public class ReportServlet extends HttpServlet {

	/**
	 * Serial Version UID
	 */
	private static final long serialVersionUID = -2521460765422068784L;

	private static final String REPORTID_PARAM = "_rid";
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/pdf");

		ReportService reportService = (ReportService)WebApplicationContextUtils.getWebApplicationContext(this.getServletContext())
		.getBean("reportService");
		
		ReportContext context = new ReportContext();
		context.setQueryParams(convertRequest2Map(request));
		context.setOutput(response.getOutputStream());
		try {
			reportService.export(request.getParameter(REPORTID_PARAM), context);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 将请求参数放到Map
	 * @param request 请求
	 * @return 参数Map
	 */
	@SuppressWarnings({ "unchecked" })
	private Map<String, Object> convertRequest2Map(HttpServletRequest request) {
		Map<String, Object> newMap = new HashMap<String, Object>();
		Map<String, Object> parameterMap = request.getParameterMap();
		if (parameterMap == null) {
			parameterMap = Collections.EMPTY_MAP;
		} else {
			Set<String> keys = parameterMap.keySet();
			for (String key : keys) {
				String[] values = (String[]) parameterMap.get(key);
				// 过滤关键字
				if (REPORTID_PARAM.equals(key)) {
					continue;
				}
				// 解决数组参数不能完全编解码问题
				if (values != null) {
					for (int i = 0; i < values.length; i++) {
						try {
							values[i] = URLDecoder.decode(values[i], "UTF-8");
						} catch (UnsupportedEncodingException e) {
							throw new ReportException("error http parameter[key:" + key + "].caused by:" + e.getMessage());
						}
					}
					if (values.length == 1) {
						newMap.put(key, values[0]);
					} else {
						newMap.put(key, values);
					}
				}
			}
		}
		return newMap;
	}
}